package org.egrit.util;

import org.egrit.geometry.PointCoordinateSequence;
import org.egrit.geometry.GeometryUtils;
import com.vividsolutions.jts.geom.Polygonal;
import com.vividsolutions.jts.geom.prep.PreparedPolygon;


/**
 * Used to efficiently do a series of point in polygon tests on a grid polygon
 * (ie. one having edges which correspond to grid cell boundaries). Can be used
 * with both Polygon and MultiPolygon objects.
 *
 * @author michael
 */
public class GridPosInPolygonTester {
    
    private final PointCoordinateSequence coordSeq;
    private final com.vividsolutions.jts.geom.Point testPoint;
    private final PreparedPolygon targetPoly;
    
    public GridPosInPolygonTester(Polygonal poly) {
        this.targetPoly = new PreparedPolygon(poly);
        this.coordSeq = new PointCoordinateSequence();
        this.testPoint = GeometryUtils.getGeometryFactory().createPoint(coordSeq);
    }
    
    public boolean isWithin(int gridX, int gridY) {
        coordSeq.setXY(gridX + 0.5, gridY + 0.5);
        testPoint.geometryChanged();
        return targetPoly.contains(testPoint);
    }

    public boolean isWithin(java.awt.Point gridPos) {
        Args.notNull("gridPos", gridPos);
        return isWithin(gridPos.x, gridPos.y);
    }
    
}
